<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>电子相册系统</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<!-- 主页面 -->
<div id="mainView" class="page" aria-hidden="true">
  <header class="app-header">
    <div class="logo"><div class="mark">EA</div><div><div style="font-weight:800">电子相册</div><div class="muted" style="font-size:13px">分享 · 收藏 · 回忆</div></div></div>

    <div class="search"><input id="searchInput" placeholder="搜索相册 / 用户 / 标签" oninput="renderAlbums()"></div>

    <div class="user-area">
      <div id="userName" style="font-weight:700">用户名</div>
      <div class="avatar" id="userAvatar">U</div>
      <button class="btn ghost" onclick="window.location.href='/userinfo'">个人中心</button>
      <button class="btn ghost" onclick="window.location.href='/createalbum'">➕ 相册</button>
      <button class="btn ghost" onclick="logout()">登出</button>
    </div>
  </header>


  <div class="categories" id="categories"></div>

  <main>
    <section id="albumGrid" class="album-grid" aria-live="polite"></section>
  </main>

</div>


<script>
  window.onload = function() {
    loadUserInfo();
    loadCategories();
  }

  let allAlbums = [];
  let selectedCategory = '';

  function loadUserInfo() {
    fetch('/getuserinfo')
      .then(res => res.json())
      .then(data => {
        if( !data.username ) {
          alert('未登录或登录已过期，请重新登录。');
          window.location.href = '/';
          return;
        }
        document.getElementById('userName').innerText = "你好" + data.username;
        document.getElementById('userAvatar').innerText = data.username.charAt(0).toUpperCase();
        renderAlbums();
      });
  }

  function loadCategories() {
    fetch('/getcategorylist')
      .then(res => res.json())
      .then(categories => {
        const catDiv = document.getElementById('categories');
        catDiv.innerHTML = '';
        const allBtn = document.createElement('div');
        allBtn.className = 'chip' + (selectedCategory==='' ? ' active' : '');
        allBtn.textContent = '全部';
        allBtn.onclick = () => { selectedCategory = ''; renderAlbums(); highlightCategory(); };
        catDiv.appendChild(allBtn);
        categories.forEach(cat => {
          const btn = document.createElement('div');
          btn.className = 'chip' + (selectedCategory===cat ? ' active' : '');
          btn.textContent = cat;
          btn.onclick = () => { selectedCategory = cat; renderAlbums(); highlightCategory(); };
          catDiv.appendChild(btn);
        });
      });
    // 加载所有相册
    fetch('/getallalbumsbrief')
      .then(res => res.json())
      .then(albums => {
        allAlbums = albums;
        console.log(allAlbums);
        renderAlbums();
      });
  }

  function highlightCategory() {
    const chips = document.querySelectorAll('#categories .chip');
    chips.forEach(chip => {
      chip.classList.remove('active');
      if ((selectedCategory === '' && chip.textContent === '全部') || chip.textContent === selectedCategory) {
        chip.classList.add('active');
      }
    });
  }

  function renderAlbums() {
    const grid = document.getElementById('albumGrid');
    grid.innerHTML = '';
    let albums = allAlbums;
    if (selectedCategory) {
      albums = albums.filter(a => a.category === selectedCategory);
    }
    albums.forEach(album => {
      const card = document.createElement('div');
      card.className = 'album-card';
      card.style.cursor = 'pointer';
      card.onclick = () => window.location.href = `/album/${album.albumId}`;
      let coverHtml = '';
      if (album.coverUrl) {
        coverHtml = `<img src="${album.coverUrl}" alt="封面" style="height:260px;object-fit:cover;">`;
      } else {
        coverHtml = `<div style="height:260px;display:flex;align-items:center;justify-content:center;background:#eee;font-size:32px;color:#888;font-weight:700;">${album.title}</div>`;
      }
      card.innerHTML = `
        ${coverHtml}
        <div class="meta">
          <div class="title">${album.title}</div>
          <div class="info">作者：${album.author} | 类别：${album.category}</div>
        </div>
      `;
      grid.appendChild(card);
    });
  }

  function logout() {
    fetch('/logout')
      .then(() => {
        alert('已登出');
        window.location.href = '/'; // 登出后跳转到登录页面
      });
  }
  function addcategory() {
    const categoryName = prompt('请输入新类别名称：');
    if (!categoryName) return;
    fetch('/addcategory', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ categoryname: categoryName })
    })
    .then(res => res.json())
    .then(data => {
      if (data.success) {
        alert('类别添加成功！');
        loadCategories();
      } else {
        alert('类别添加失败：' + data.message);
      }
    });
  }
</script>
</body>
</html>
